package com.xtayfjpk.expressionj.test;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.da.expressionj.expr.parser.EquationParser;
import org.da.expressionj.expr.parser.ParseException;
import org.da.expressionj.functions.FunctionsDefinitions;
import org.da.expressionj.model.Equation;
import org.da.expressionj.model.Variable;

public class EquationUtil {
	private final static Map<String, Equation> equationMap;
	private final static FunctionsDefinitions def;

	private EquationUtil() {}

	static {
		equationMap = new HashMap<>();
		def = FunctionsDefinitions.getInstance();
	}


	public static void regist(Class<? extends Function> clz) throws InstantiationException, IllegalAccessException {
		Function function = clz.newInstance();
		Method[] methods = clz.getMethods();
		for(Method method : methods) {
			def.addFunction(method.getName(), function, method);
		}
	}

	public static void reset() {
		def.reset();
	}


	public static Equation getEquation(String expr) throws ParseException {
		Equation equation = equationMap.get(expr);
		if(equation == null) {
			equation = EquationParser.parse(expr);
			equationMap.put(expr, equation);
		}
		return equation;
	}

	public static Object evaluate(String expr, Map<String, Object> map) throws ParseException {
		Equation equation = getEquation(expr);
		Map<String, Variable> vars = equation.getVariables();
		for(String key : vars.keySet()) {
			vars.get(key).setValue(map.get(key));
		}
		return equation.eval();
	}
}
